<!DOCTYPE html>
<html lang="en-US">
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width,initial-scale=1">
    <title>Vue.js中 watch 的高级用法 | 砖业洋__</title>
    <meta name="generator" content="VuePress 1.5.2">
    <link rel="icon" href="/haizei.jpg">
    <meta name="description" content="">
    <link rel="preload" href="/assets/css/0.styles.1f351a1e.css" as="style"><link rel="preload" href="/assets/js/app.1c226385.js" as="script"><link rel="preload" href="/assets/js/2.5bd328db.js" as="script"><link rel="preload" href="/assets/js/3.90e623d3.js" as="script"><link rel="preload" href="/assets/js/12.0c5442fd.js" as="script"><link rel="prefetch" href="/assets/js/10.4eb1cc28.js"><link rel="prefetch" href="/assets/js/11.cd070e67.js"><link rel="prefetch" href="/assets/js/4.3a00ff1b.js"><link rel="prefetch" href="/assets/js/5.9f70a21c.js"><link rel="prefetch" href="/assets/js/6.db1982cd.js"><link rel="prefetch" href="/assets/js/7.46572acb.js"><link rel="prefetch" href="/assets/js/8.2b398bc4.js"><link rel="prefetch" href="/assets/js/9.f2979413.js">
    <link rel="stylesheet" href="/assets/css/0.styles.1f351a1e.css">
  </head>
  <body>
    <div id="app" data-server-rendered="true"><div class="theme-container"><!----> <!----> <header class="navbar"><div class="sidebar-button"><svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" role="img" viewBox="0 0 448 512" class="icon"><path fill="currentColor" d="M436 124H12c-6.627 0-12-5.373-12-12V80c0-6.627 5.373-12 12-12h424c6.627 0 12 5.373 12 12v32c0 6.627-5.373 12-12 12zm0 160H12c-6.627 0-12-5.373-12-12v-32c0-6.627 5.373-12 12-12h424c6.627 0 12 5.373 12 12v32c0 6.627-5.373 12-12 12zm0 160H12c-6.627 0-12-5.373-12-12v-32c0-6.627 5.373-12 12-12h424c6.627 0 12 5.373 12 12v32c0 6.627-5.373 12-12 12z"></path></svg></div> <a href="/" class="home-link router-link-active"><img src="/haizei.jpg" alt="砖业洋__" class="logo"> <span class="site-name can-hide">砖业洋__</span></a> <div class="links"><span>你好，砖业洋__持续为你分享    </span> <div class="search-box"><input aria-label="Search" autocomplete="off" spellcheck="false" value=""> <!----></div> <nav class="nav-links can-hide"><div class="nav-item"><a href="/" class="nav-link">
  首页
</a></div><div class="nav-item"><a href="https://liuchenyang0515.blog.csdn.net" target="_blank" rel="noopener noreferrer" class="nav-link external">
  CSDN主页
  <svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" x="0px" y="0px" viewBox="0 0 100 100" width="15" height="15" class="icon outbound"><path fill="currentColor" d="M18.8,85.1h56l0,0c2.2,0,4-1.8,4-4v-32h-8v28h-48v-48h28v-8h-32l0,0c-2.2,0-4,1.8-4,4v56C14.8,83.3,16.6,85.1,18.8,85.1z"></path> <polygon fill="currentColor" points="45.7,48.7 51.3,54.3 77.2,28.5 77.2,37.2 85.2,37.2 85.2,14.9 62.8,14.9 62.8,22.9 71.5,22.9"></polygon></svg></a></div> <!----></nav></div></header> <div class="sidebar-mask"></div> <aside class="sidebar"><nav class="nav-links"><div class="nav-item"><a href="/" class="nav-link">
  首页
</a></div><div class="nav-item"><a href="https://liuchenyang0515.blog.csdn.net" target="_blank" rel="noopener noreferrer" class="nav-link external">
  CSDN主页
  <svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" x="0px" y="0px" viewBox="0 0 100 100" width="15" height="15" class="icon outbound"><path fill="currentColor" d="M18.8,85.1h56l0,0c2.2,0,4-1.8,4-4v-32h-8v28h-48v-48h28v-8h-32l0,0c-2.2,0-4,1.8-4,4v56C14.8,83.3,16.6,85.1,18.8,85.1z"></path> <polygon fill="currentColor" points="45.7,48.7 51.3,54.3 77.2,28.5 77.2,37.2 85.2,37.2 85.2,14.9 62.8,14.9 62.8,22.9 71.5,22.9"></polygon></svg></a></div> <!----></nav>  <ul class="sidebar-links"><li><section class="sidebar-group depth-0"><p class="sidebar-heading open"><span>Vue.js中 watch 的高级用法</span> <!----></p> <ul class="sidebar-links sidebar-group-items"><li><a href="/tech/watch_gaojiyongfa.html#handler方法和immediate属性" class="sidebar-link">handler方法和immediate属性</a><ul class="sidebar-sub-headers"></ul></li><li><a href="/tech/watch_gaojiyongfa.html#deep属性" class="sidebar-link">deep属性</a><ul class="sidebar-sub-headers"></ul></li><li><a href="/tech/watch_gaojiyongfa.html#注销watch" class="sidebar-link">注销watch</a><ul class="sidebar-sub-headers"></ul></li></ul></section></li></ul> </aside> <main class="page"> <div class="theme-default-content content__default"><h1 id="vue-js中-watch-的高级用法"><a href="#vue-js中-watch-的高级用法" class="header-anchor">#</a> Vue.js中 watch 的高级用法</h1> <blockquote><p>作者：杜尼卜</p></blockquote> <p>假设有如下代码：</p> <div class="language-javascript extra-class"><pre class="language-javascript"><code><span class="token operator">&lt;</span>div<span class="token operator">&gt;</span>
      <span class="token operator">&lt;</span>p<span class="token operator">&gt;</span>FullName<span class="token operator">:</span> <span class="token punctuation">{</span><span class="token punctuation">{</span>fullName<span class="token punctuation">}</span><span class="token punctuation">}</span><span class="token operator">&lt;</span><span class="token operator">/</span>p<span class="token operator">&gt;</span>
      <span class="token operator">&lt;</span>p<span class="token operator">&gt;</span>FirstName<span class="token operator">:</span> <span class="token operator">&lt;</span>input type<span class="token operator">=</span><span class="token string">&quot;text&quot;</span> v<span class="token operator">-</span>model<span class="token operator">=</span><span class="token string">&quot;firstName&quot;</span><span class="token operator">&gt;</span><span class="token operator">&lt;</span><span class="token operator">/</span>p<span class="token operator">&gt;</span>
<span class="token operator">&lt;</span><span class="token operator">/</span>div<span class="token operator">&gt;</span>

<span class="token keyword">new</span> <span class="token class-name">Vue</span><span class="token punctuation">(</span><span class="token punctuation">{</span>
  el<span class="token operator">:</span> <span class="token string">'#root'</span><span class="token punctuation">,</span>
  data<span class="token operator">:</span> <span class="token punctuation">{</span>
    firstName<span class="token operator">:</span> <span class="token string">'Dawei'</span><span class="token punctuation">,</span>
    lastName<span class="token operator">:</span> <span class="token string">'Lou'</span><span class="token punctuation">,</span>
    fullName<span class="token operator">:</span> <span class="token string">''</span>
  <span class="token punctuation">}</span><span class="token punctuation">,</span>
  watch<span class="token operator">:</span> <span class="token punctuation">{</span>
    <span class="token function">firstName</span><span class="token punctuation">(</span><span class="token parameter">newName<span class="token punctuation">,</span> oldName</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
      <span class="token keyword">this</span><span class="token punctuation">.</span>fullName <span class="token operator">=</span> newName <span class="token operator">+</span> <span class="token string">' '</span> <span class="token operator">+</span> <span class="token keyword">this</span><span class="token punctuation">.</span>lastName<span class="token punctuation">;</span>
    <span class="token punctuation">}</span>
  <span class="token punctuation">}</span> 
<span class="token punctuation">}</span><span class="token punctuation">)</span>
</code></pre></div><p>上面的代码的效果是，当我们输入<code>firstName</code>后，<code>wacth</code>监听每次修改变化的新值，然后计算输出<code>fullName</code>。</p> <h2 id="handler方法和immediate属性"><a href="#handler方法和immediate属性" class="header-anchor">#</a> handler方法和immediate属性</h2> <p>这里 watch 的一个特点是，最初绑定的时候是不会执行的，要等到 <code>firstName</code> 改变时才执行监听计算。那我们想要一开始就让他最初绑定的时候就执行改怎么办呢？我们需要修改一下我们的 watch 写法，修改过后的 watch 代码如下：</p> <div class="language-javascript extra-class"><pre class="language-javascript"><code>watch<span class="token operator">:</span> <span class="token punctuation">{</span>
  firstName<span class="token operator">:</span> <span class="token punctuation">{</span>
    <span class="token function">handler</span><span class="token punctuation">(</span><span class="token parameter">newName<span class="token punctuation">,</span> oldName</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
      <span class="token keyword">this</span><span class="token punctuation">.</span>fullName <span class="token operator">=</span> newName <span class="token operator">+</span> <span class="token string">' '</span> <span class="token operator">+</span> <span class="token keyword">this</span><span class="token punctuation">.</span>lastName<span class="token punctuation">;</span>
    <span class="token punctuation">}</span><span class="token punctuation">,</span>
    <span class="token comment">// 代表在wacth里声明了firstName这个方法之后立即先去执行handler方法</span>
    immediate<span class="token operator">:</span> <span class="token boolean">true</span>
  <span class="token punctuation">}</span>
<span class="token punctuation">}</span>
</code></pre></div><p>注意到<code>handler</code>了吗，我们给 firstName 绑定了一个<code>handler</code>方法，之前我们写的 watch 方法其实默认写的就是这个<code>handler</code>，Vue.js会去处理这个逻辑，最终编译出来其实就是这个<code>handler</code>。</p> <p>而<code>immediate:true</code>代表如果在 wacth 里声明了 firstName 之后，就会立即先去执行里面的handler方法，如果为 <code>false</code>就跟我们以前的效果一样，不会在绑定的时候就执行。</p> <h2 id="deep属性"><a href="#deep属性" class="header-anchor">#</a> deep属性</h2> <p>watch 里面还有一个属性 <code>deep</code>，默认值是 <code>false</code>，代表是否深度监听，比如我们 data 里有一个<code>obj</code>属性：</p> <div class="language-html extra-class"><pre class="language-html"><code><span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>div</span><span class="token punctuation">&gt;</span></span>
      <span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>p</span><span class="token punctuation">&gt;</span></span>obj.a: {{obj.a}}<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;/</span>p</span><span class="token punctuation">&gt;</span></span>
      <span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>p</span><span class="token punctuation">&gt;</span></span>obj.a: <span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>input</span> <span class="token attr-name">type</span><span class="token attr-value"><span class="token punctuation">=</span><span class="token punctuation">&quot;</span>text<span class="token punctuation">&quot;</span></span> <span class="token attr-name">v-model</span><span class="token attr-value"><span class="token punctuation">=</span><span class="token punctuation">&quot;</span>obj.a<span class="token punctuation">&quot;</span></span><span class="token punctuation">&gt;</span></span><span class="token tag"><span class="token tag"><span class="token punctuation">&lt;/</span>p</span><span class="token punctuation">&gt;</span></span>
<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;/</span>div</span><span class="token punctuation">&gt;</span></span>

new Vue({
  el: '#root',
  data: {
    obj: {
      a: 123
    }
  },
  watch: {
    obj: {
      handler(newName, oldName) {
         console.log('obj.a changed');
      },
      immediate: true
    }
  } 
})
</code></pre></div><p>当我们在在输入框中输入数据视图改变<code>obj.a</code>的值时，我们发现是无效的。受现代 JavaScript 的限制 (以及废弃 <code>Object.observe</code>)，Vue 不能检测到对象属性的添加或删除。由于 Vue 会在初始化实例时对属性执行 <code>getter/setter</code> 转化过程，所以属性必须在 <code>data</code> 对象上存在才能让 Vue 转换它，这样才能让它是响应的。</p> <p>默认情况下 handler 只监听<code>obj</code>这个属性它的引用的变化，我们只有给<code>obj</code>赋值的时候它才会监听到，比如我们在 mounted事件钩子函数中对<code>obj</code>进行重新赋值：</p> <div class="language-javascript extra-class"><pre class="language-javascript"><code>mounted<span class="token operator">:</span> <span class="token punctuation">{</span>
  <span class="token keyword">this</span><span class="token punctuation">.</span>obj <span class="token operator">=</span> <span class="token punctuation">{</span>
    a<span class="token operator">:</span> <span class="token string">'456'</span>
  <span class="token punctuation">}</span>
<span class="token punctuation">}</span>
</code></pre></div><p>这样我们的 handler 才会执行，打印<code>obj.a changed</code>。</p> <p>相反，如果我们需要监听<code>obj</code>里的属性<code>a</code>的值呢？这时候<code>deep</code>属性就派上用场了！</p> <div class="language-javascript extra-class"><pre class="language-javascript"><code>watch<span class="token operator">:</span> <span class="token punctuation">{</span>
  obj<span class="token operator">:</span> <span class="token punctuation">{</span>
    <span class="token function">handler</span><span class="token punctuation">(</span><span class="token parameter">newName<span class="token punctuation">,</span> oldName</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
      console<span class="token punctuation">.</span><span class="token function">log</span><span class="token punctuation">(</span><span class="token string">'obj.a changed'</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token punctuation">}</span><span class="token punctuation">,</span>
    immediate<span class="token operator">:</span> <span class="token boolean">true</span><span class="token punctuation">,</span>
    deep<span class="token operator">:</span> <span class="token boolean">true</span>
  <span class="token punctuation">}</span>
<span class="token punctuation">}</span> 
</code></pre></div><p><code>deep</code>的意思就是深入观察，监听器会一层层的往下遍历，给对象的所有属性都加上这个监听器，但是这样性能开销就会非常大了，任何修改<code>obj</code>里面任何一个属性都会触发这个监听器里的 handler。</p> <p>优化，我们可以是使用字符串形式监听。</p> <div class="language-javascript extra-class"><pre class="language-javascript"><code>watch<span class="token operator">:</span> <span class="token punctuation">{</span>
  <span class="token string">'obj.a'</span><span class="token operator">:</span> <span class="token punctuation">{</span>
    <span class="token function">handler</span><span class="token punctuation">(</span><span class="token parameter">newName<span class="token punctuation">,</span> oldName</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
      console<span class="token punctuation">.</span><span class="token function">log</span><span class="token punctuation">(</span><span class="token string">'obj.a changed'</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token punctuation">}</span><span class="token punctuation">,</span>
    immediate<span class="token operator">:</span> <span class="token boolean">true</span><span class="token punctuation">,</span>
    <span class="token comment">// deep: true</span>
  <span class="token punctuation">}</span>
<span class="token punctuation">}</span>
</code></pre></div><p>这样Vue.js才会一层一层解析下去，直到遇到属性<code>a</code>，然后才给<code>a</code>设置监听函数。</p> <h2 id="注销watch"><a href="#注销watch" class="header-anchor">#</a> 注销watch</h2> <p>为什么要注销 <code>watch</code>？因为我们的组件是经常要被销毁的，比如我们跳一个路由，从一个页面跳到另外一个页面，那么原来的页面的 watch 其实就没用了，这时候我们应该注销掉原来页面的 watch 的，不然的话可能会导致内置溢出。好在我们平时 watch 都是写在组件的选项中的，他会随着组件的销毁而销毁。</p> <div class="language-javascript extra-class"><pre class="language-javascript"><code><span class="token keyword">const</span> app <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">Vue</span><span class="token punctuation">(</span><span class="token punctuation">{</span>
  template<span class="token operator">:</span> <span class="token string">'&lt;div id=&quot;root&quot;&gt;{{text}}&lt;/div&gt;'</span><span class="token punctuation">,</span>
  data<span class="token operator">:</span> <span class="token punctuation">{</span>
    text<span class="token operator">:</span> <span class="token number">0</span>
  <span class="token punctuation">}</span><span class="token punctuation">,</span>
  watch<span class="token operator">:</span> <span class="token punctuation">{</span>
    <span class="token function">text</span><span class="token punctuation">(</span><span class="token parameter">newVal<span class="token punctuation">,</span> oldVal</span><span class="token punctuation">)</span><span class="token punctuation">{</span>
      console<span class="token punctuation">.</span><span class="token function">log</span><span class="token punctuation">(</span><span class="token template-string"><span class="token template-punctuation string">`</span><span class="token interpolation"><span class="token interpolation-punctuation punctuation">${</span>newVal<span class="token interpolation-punctuation punctuation">}</span></span><span class="token string"> : </span><span class="token interpolation"><span class="token interpolation-punctuation punctuation">${</span>oldVal<span class="token interpolation-punctuation punctuation">}</span></span><span class="token template-punctuation string">`</span></span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token punctuation">}</span>
  <span class="token punctuation">}</span>
<span class="token punctuation">}</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
</code></pre></div><p>但是，如果我们使用下面这样的方式写 watch，那么就要手动注销了，这种注销其实也很简单</p> <div class="language-javascript extra-class"><pre class="language-javascript"><code><span class="token keyword">const</span> unWatch <span class="token operator">=</span> app<span class="token punctuation">.</span><span class="token function">$watch</span><span class="token punctuation">(</span><span class="token string">'text'</span><span class="token punctuation">,</span> <span class="token punctuation">(</span><span class="token parameter">newVal<span class="token punctuation">,</span> oldVal</span><span class="token punctuation">)</span> <span class="token operator">=&gt;</span> <span class="token punctuation">{</span>
  console<span class="token punctuation">.</span><span class="token function">log</span><span class="token punctuation">(</span><span class="token template-string"><span class="token template-punctuation string">`</span><span class="token interpolation"><span class="token interpolation-punctuation punctuation">${</span>newVal<span class="token interpolation-punctuation punctuation">}</span></span><span class="token string"> : </span><span class="token interpolation"><span class="token interpolation-punctuation punctuation">${</span>oldVal<span class="token interpolation-punctuation punctuation">}</span></span><span class="token template-punctuation string">`</span></span><span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token punctuation">}</span><span class="token punctuation">)</span>

<span class="token function">unWatch</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span> <span class="token comment">// 手动注销watch</span>
</code></pre></div><p><code>app.$watch</code>调用后会返回一个值，就是<code>unWatch</code>方法，你要注销 watch 只要调用<code>unWatch</code>方法就可以了。</p> <br> <!----></div> <footer class="page-edit"><!----> <!----></footer> <!----> </main></div><div class="global-ui"></div></div>
    <script src="/assets/js/app.1c226385.js" defer></script><script src="/assets/js/2.5bd328db.js" defer></script><script src="/assets/js/3.90e623d3.js" defer></script><script src="/assets/js/12.0c5442fd.js" defer></script>
  </body>
</html>
